import { useMutation } from "react-relay";
import {useCallback, useState} from "react";
import {useToast} from "customize-easy-ui-component";
import * as React from "react";
const graphql = require("babel-plugin-relay/macro");

/*新建立task: 必须最少有个设备？(无关联设备号的单独报告的任务？)
先生成task后面再来添加eqp;
* */
const mutation = graphql`
    mutation useOriginalDataMutation(
        $id: ID! 
        $operationType:Int!
        $data: String
        $deduction: String, $version:Int
    ) {
      modifyOriginalRecordData(id: $id, operationType: $operationType, data: $data, deduction: $deduction,version: $version) {
          id,version,type
          data
          snapshot
          modeltype,modelversion
          isp{id}
      }
    }
`;

export default function useOriginalDataMutation(callback: (result: any) => void) {
  const [called, setCalled] =useState<boolean>(false);
  const [result, setResult] =useState<any>('');
  const [commit, doing] = useMutation(mutation);
  const toast = useToast();
  return {
    call:useCallback(
      (id:string, operationType:number, data: string,deduction: string,version: number) => {
        let disposable= commit({
          variables: {
            id, operationType, data, deduction, version
          },
          onCompleted: (response) => {
            setResult((response as any).modifyOriginalRecordData);
              callback((response as any).modifyOriginalRecordData);
            toast({
              title: "后端应答",
              subtitle: '完成提交了，报告ID＝'+ (response as any).modifyOriginalRecordData.id,
              intent: "info"
            });
           },
           onError: error => {
                toast({
                    title: "后端应答",
                    subtitle: ""+error,
                    intent: "warning"
                });
            }
        });
        //必须放在commit函数之后的，才会doing逻辑=true生效,doing+called逻辑,保障同步化
        setCalled(true);
        return disposable;
      },
      [commit,toast]
    ),
    doing,
    result,
    called,
    reset: ()=>setCalled(false),
  };
}
